package socket

import (
	"crypto/rand"
	"encoding/json"
	"gdfs-service/conf"
	"gdfs-service/utils"
	"math"
	"math/big"
)

//生成存储服务器信息上报命令
func GenerateUploadInfoCmd(weight int, nodeid, httpport, storeid string) []byte {
	var storeinfo UploadStoreInfo
	storeinfo.Weight = weight
	storeinfo.NodeId = nodeid
	storeinfo.HttpPort = httpport
	storeinfo.IP = utils.GetInternetIp()
	storeinfo.ID = storeid
	storeinfojson, _ := json.Marshal(storeinfo)
	resp := GenerateSendMsg(1, storeinfojson)
	return EncoderData(resp)
}

//生成心跳命令
func GenerateHeartBeatCmd() []byte {
	var h HeartBeatInfo
	storeid := conf.GetStoreid() //获取nodeid
	h.ID = storeid
	heartbeatjson, _ := json.Marshal(h)
	resp := GenerateSendMsg(2, heartbeatjson)
	return EncoderData(resp)
}

//生成迁移数据库数据指令
func GenerateTransferDbCmd(syncdb SyncDb) []byte {
	syncjson, _ := json.Marshal(syncdb)
	resp := GenerateSendMsg(8, syncjson)
	return EncoderData(resp)
}

//生成上报服务系统信息
func GenerateUploadFileSysInfo(info UploadHardWareInfo) []byte {
	infojson, _ := json.Marshal(info)
	resp := GenerateSendMsg(10, infojson)
	return EncoderData(resp)
}

//生成创建TCP服务返回指令
func GenerateCreateTcpServerResult(t TranmitServerResultCmd) []byte {
	resultjson, _ := json.Marshal(t)
	resp := GenerateSendMsg(9, resultjson)
	return EncoderData(resp)
}

// 生成区间[-m, n]的安全随机数
func RangeRand(min, max int64) int64 {
	if min > max {
		panic("the min is greater than max!")
	}

	if min < 0 {
		f64Min := math.Abs(float64(min))
		i64Min := int64(f64Min)
		result, _ := rand.Int(rand.Reader, big.NewInt(max+1+i64Min))

		return result.Int64() - i64Min
	} else {
		result, _ := rand.Int(rand.Reader, big.NewInt(max-min+1))
		return min + result.Int64()
	}
}

//生成生成发送指令
func GenerateSendMsg(cmd int, jsonb []byte) *Response {
	resp := &Response{
		SerialNum: uint64(RangeRand(1, 1025)),
		Cmd:       cmd,
		Data:      jsonb,
	}
	return resp
}

//生成反馈进度指令
func GenerateSyncData(p SyncPercent) []byte {
	jsonb, _ := json.Marshal(p)
	return EncoderData(GenerateSendMsg(5, jsonb))
}
